package it.bit.jlightqueryer.conn;

import java.io.File;
import java.io.FileFilter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Class to handle JLQ available drivers
 * @author PerezDeQueya80
 */
public class Drivers {
	private static Driver[] drivers = null;

	/**
	 * @return main static available drivers;
	 */
	public static Driver[] getDrivers() {
		if (drivers==null)
			drivers = getAvailableDrivers();
		return drivers;
	}

	/**
	 * @return available drivers loaded from file system
	 */
	public static Driver[] getAvailableDrivers() {
		List drivers = new ArrayList();
		try {
			URL driversDirURL = Drivers.class.getResource("/JLQDrivers");
			if (driversDirURL==null) {
				driversDirURL = new File("JLQDrivers").toURL();
			}
			File driversDir = new File(new URI(driversDirURL.toString()));
			if (driversDir.exists()) {
				File[] driversDirs = driversDir.listFiles(new FileFilter(){
					public boolean accept(File pathname) {
						return pathname.isDirectory();
					}
				});
				for (int i = 0; i < driversDirs.length; i++) {
					try {
						File driverDir = driversDirs[i];
						File driverPropFile = new File(driverDir+File.separator+"driver.properties");
						if (driverPropFile.exists()) {
							Driver driver = new Driver(driverPropFile);
							if (driver.load())
								drivers.add(driver);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		Driver[] result = new Driver[drivers.size()];
		for (int i = 0; i < result.length; i++) {
			result[i] = (Driver) drivers.get(i);
		}
		return result;
	}

	/**
	 * @param driver identifier
	 * @return the Driver identified by id
	 */
	public static Driver get(String id) {
		for (int i = 0; i < getDrivers().length; i++) {
			Driver driver = getDrivers()[i];
			if (driver.getId().equals(id))
				return driver;
		}
		return null;
	}
}
